import { create } from 'zustand';
import { getIframeRoutes } from '@/api/integration'

import { useUserToken } from './userStore';
import { useNavigate } from 'react-router-dom';
import { isExternal, getLocation } from '../utils';
const menuFilter = (arr) => {
  return arr.filter((d) => {
    if (!d.hasOwnProperty('type') || d.type === null || d.type === 1) {
      if (d.children) {
        d.children = menuFilter(d.children)
      }
      return true
    }
    return false
  })
}

const findMenuItem = (arr, code, key = 'code') => {
  let result;
  arr.find((d) => {
    if (d[key] === code) {
      result = d
      return true
    } else if (d.children) {
      result = findMenuItem(d.children, code, key)
      return Boolean(result)
    }
  })
  return result
}

const useMenuStore = create()(
  (set, get) => ({
    microMenus: [],
    menusReady: false,
    modelMenus: [],
    currentModel: undefined, // 当前选中modeId的菜单
    cacheMenus: [],
    actions: {
      setMenuReady(ready) {
        set({ menusReady: ready })
      },

      async getDashboardMenus(type = 'dataStorage') {
        const res = await getIframeRoutes({ dictTypes: 'SYS_APP_TYPE' })
        if (res.data?.length) {
          res.data = (res.data[0].appSimpleVoList || []).map(d => {
            return {
              ...d,
              code: d.appCode,
              name: d.appName,
              url: d.resUrl,
              children: menuFilter(d.resourceVos || [])
            }
          })
        }
        set({ microMenus: res.data || [] })

        set({ modelMenus: get().microMenus.find(d => d.appCode === type)?.children || [] })
        return get().modelMenus
      },
      findByCodeMenu(code) {
        const result = findMenuItem(get().modelMenus, code)
        return result
      },
      findByIdMenu(code) {
        const result = findMenuItem(get().modelMenus, code, 'id')
        return result
      },
      selectedByCode(data) {
        let result;
        if (typeof data === 'number' || typeof data === 'string') {
          result = findMenuItem(get().modelMenus, data)
        } else {
          result = data
        }
        result && set({ currentModel: result })
        return result
      },

      setCacheMenus(data) {
        set({ cacheMenus: data })
      }
    },
  })
);

export const useCacheMenus = () => useMenuStore((state) => state.cacheMenus);
export const useMenuData = () => useMenuStore((state) => state.modelMenus);
export const useMenuSelected = () => useMenuStore((state) => state.currentModel);
export const useMenuActions = () => useMenuStore((state) => state.actions);

export const useSkipContainer = () => {
  const navigatge = useNavigate();
  const token = useUserToken();
  const { selectedByCode } = useMenuActions();
  // 根据菜单配置选择是否跳转到容器
  const skipContainer = async (activeMenu) => {
    let path = activeMenu.url || activeMenu.path
    if (!activeMenu || !path) return
    // routerMethod 加载方式:1嵌入 2s独立
    // openMethod 打开方式:1内部 2外部
    let url = path;
    let appid = activeMenu.appId ? `&menuTopId=${activeMenu.appId}` : ''
    let menuCode = activeMenu.menuCode ? `&menuCode=${activeMenu.code}` : ''
    if (activeMenu.routerMethod == 1) {
      url = `/integration/index?&menuUrl=${encodeURIComponent(url)}${appid}${menuCode}`
    }
    if (activeMenu.openMethod == 2) {
      window.open(`${url}${url.includes('?') ? '&' : '?'}token=${token}`)
    } else {
      selectedByCode(activeMenu)
      if (isExternal(url)) {
        getLocation().href = `${url}${url.includes('?') ? '&' : '?'}token=${token}`
      } else {
        navigatge(url + '&time=' + new Date().getTime());
      }
    }
  };
  return skipContainer;
};



const getDevUrl = (url) => {
  let urlObj = new URL(url)
  let devLs = import.meta.env.VITE_APP_XIANWAANG.split(',')
  if (devLs.find((s) => url.includes(s))) {
    return urlObj.pathname
  }
  return url
}

export const useSkipDirect = () => {
  const navigate = useNavigate();
  const token = useUserToken();
  const { selectedByCode } = useMenuActions();
  // 根据菜单配置选择是否跳转到容器
  const skipDirect = async (activeMenu) => {
    let path = activeMenu.url || activeMenu.path
    if (!activeMenu || !path) return
    // routerMethod 加载方式:1嵌入 2独立
    // openMethod 打开方式:1内部 2外部
    let url = path;
    // if (activeMenu.routerMethod == 1) {
    //   url = `/Container?menuTopId=${activeMenu.appId}&menuCode=${activeMenu.code}&menuUrl=${encodeURIComponent(url)}`
    // }
    if (activeMenu.openMethod == 2) {
      window.open(`${url}${url.includes('?') ? '&' : '?'}token=${token}`)
    } else {

      if (isExternal(url) && import.meta.env.MODE === 'development') {
        url = getDevUrl(url)
      }
      if (isExternal(url)) {
        if (url.includes(getLocation().origin)) {
          selectedByCode(activeMenu)
          navigate(url.replace(getLocation().origin, ''))
        } else {
          getLocation().href = `${url}${url.includes('?') ? '&' : '?'}token=${token}`
        }
      } else {
        selectedByCode(activeMenu)
        navigate(url);
      }
    }
  };
  return skipDirect;
};

export default useMenuStore;
